import yaml
from pathlib import Path
from typing import Dict, Any


class ConfigLoader:
    """配置加载器，支持YAML文件解析和参数引用"""

    def __init__(self, config_path: str):
        self.config = self._load_yaml(config_path)
        self._resolve_references()

    def _load_yaml(self, path: str) -> Dict[str, Any]:
        """加载YAML配置文件"""
        with open(path, "r", encoding="utf-8") as f:
            return yaml.safe_load(f)

    def _resolve_references(self):
        """解析配置中的参数引用（如${global_params.random_state}）"""

        def _resolve(value):
            if isinstance(value, str) and value.startswith("${") and value.endswith("}"):
                # 解析引用路径，如"global_params.random_state"
                ref_path = value[2:-1].split(".")
                current = self.config
                for key in ref_path:
                    current = current[key]
                return current
            elif isinstance(value, dict):
                return {k: _resolve(v) for k, v in value.items()}
            elif isinstance(value, list):
                return [_resolve(v) for v in value]
            return value

        self.config = _resolve(self.config)

    def get(self, key: str, default: Any = None) -> Any:
        """获取配置值，支持多级路径（如"paths.data_dir"）"""
        keys = key.split(".")
        current = self.config
        try:
            for k in keys:
                current = current[k]
            return current
        except (KeyError, TypeError):
            return default